package com.pijunn.users

import org.springframework.dao.DataIntegrityViolationException

import com.pijunn.common.MailingAddress;
import grails.converters.JSON

class AppUserController {
	
	/** dependency injection for the profile service */
	def profileService
	// Export service provided by Export plugin
	def exportService
	def grailsApplication  //inject GrailsApplication

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	
    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
		
		// For export
		if(params?.format && params.format != "html"){ 
			response.contentType = grailsApplication.config.grails.mime.types[params.format] 
			response.setHeader("Content-disposition", "attachment; filename=users.${params.extension}")
			
			 List fields = ["firstName", "lastName", "username", "contactEMail", "contactCellPhone", "contactOtherPhone", "contactSkypeId", 
				 "mailingAddress.address1", "mailingAddress.address2", "mailingAddress.city", "mailingAddress.state", "mailingAddress.zipCode", "mailingAddress.country",
				 "enabled", "passwordExpired"] 
			 Map labels = ["firstName": "First Name", "lastName": "Last Name", "username": "User Name", "contactEMail": "E-Mail", "contactCellPhone": "Cell Phone", "contactOtherPhone": "Other Phone", "contactSkypeId": "Skype ID", 
				 "mailingAddress.address1": "Address 1", "mailingAddress.address2": "Address 2", "mailingAddress.city": "City", "mailingAddress.state": "State/Province", "mailingAddress.zipCode": "Postal Code", "mailingAddress.country": "Country",
				 "enabled": "Enabled", "passwordExpired": "Password Reset"]
			
			// Formatter closure 
			def name = { domain, value -> 
				return domain?.lastName + ', ' + domain?.firstName 
			}
			
			Map formatters = [name: name] 
			Map parameters = [title: "Pijunn Registered Users", "column.widths": [0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.3, 0.3, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]]
			
			exportService.export(params.format, response.outputStream, AppUser.list(), fields, labels, formatters, parameters)
 		}
			
			
        [appUserInstanceList: AppUser.list(params), appUserInstanceTotal: AppUser.count()]
    }

    def create() {
        [appUserInstance: new AppUser(params), addressInstance: new MailingAddress()]
    }

    def save() {
        def appUserInstance = new AppUser(params)
		appUserInstance.createTime = new Date()
		try {
			profileService.createUser(appUserInstance, params.password)
		}
		catch(Exception e) {
            render(view: "create", model: [appUserInstance: appUserInstance,addressInstance: new MailingAddress()])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'appUser.label', default: 'AppUser'), appUserInstance.id])
        redirect(action: "show", id: appUserInstance.id)
    }

    def show(Long id) {
        def appUserInstance = AppUser.get(id)
        if (!appUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "list")
            return
        }

        [appUserInstance: appUserInstance]
    }
	
	def searchJson() {
		def users = AppUser.findAllByLastNameLikeOrFirstNameLike("%$params.id%", "%$params.id%")
		
		if(!users){
		  users = [ new AppUser([firstName:"Not", lastName:"found"]) ]
		}
		
		render users as JSON
	}

    def edit(Long id) {
        def appUserInstance = AppUser.get(id)
        if (!appUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "list")
            return
        }

        [appUserInstance: appUserInstance, addressInstance: appUserInstance.mailingAddress]
    }

    def update(Long id, Long version) {
        def appUserInstance = AppUser.get(id)
        if (!appUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (appUserInstance.version > version) {
                appUserInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'appUser.label', default: 'AppUser')] as Object[],
                          "Another user has updated this AppUser while you were editing")
                render(view: "edit", model: [appUserInstance: appUserInstance])
                return
            }
        }

        appUserInstance.properties = params

        if (!appUserInstance.save(flush: true)) {
            render(view: "edit", model: [appUserInstance: appUserInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'appUser.label', default: 'AppUser'), appUserInstance.id])
        redirect(action: "show", id: appUserInstance.id)
    }

    def delete(Long id) {
        def appUserInstance = AppUser.get(id)
        if (!appUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "list")
            return
        }

        try {
            appUserInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'appUser.label', default: 'AppUser'), id])
            redirect(action: "show", id: id)
        }
    }
}
